[Notes] TicketMaster API 2

TicketMaster API 2

Benifits of builder class


  • Easier to use because you don’t need to call a constructor with long parameter list
  • Easier to implement because you don’t need to provide constructors with different combinations of private fields.

TicketMasterAPI.java


Add getAddress

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* get the Address from the JSONObject
* @param event
* @return A String of address
* @throws JSONException
*/
private String getAddress(JSONObject event) throws JSONException {
if (!event.isNull("_embedded")) {
JSONObject embedded = event.getJSONObject("_embedded");

if (!embedded.isNull("venues")) {
JSONArray venues = embedded.getJSONArray("venues");

for (int i = 0; i < venues.length(); ++i) {
JSONObject venue = venues.getJSONObject(i);

StringBuilder sb = new StringBuilder();

if (!venue.isNull("address")) {
JSONObject address = venue.getJSONObject("address");

if (!address.isNull("line1")) {
sb.append(address.getString("line1"));
}
if (!address.isNull("line2")) {
sb.append(" ");
sb.append(address.getString("line2"));
}
if (!address.isNull("line3")) {
sb.append(" ");
sb.append(address.getString("line3"));
}
}

if (!venue.isNull("city")) {
JSONObject city = venue.getJSONObject("city");

if (!city.isNull("name")) {
sb.append(" ");
sb.append(city.getString("name"));
}
}

if (!sb.toString().equals("")) {
return sb.toString();
}
}
}
}

return "";
}

Add getImageURL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// {"images": [{"url": "www.example.com/my_image.jpg"}, ...]}
/**
* Get the image URL from a JSONOBject
* @param event
* @return A String of image URL
* @throws JSONException
*/
private String getImageUrl(JSONObject event) throws JSONException {
if (!event.isNull("images")) {
JSONArray images = event.getJSONArray("images");

for (int i = 0; i < images.length(); ++i) {
JSONObject image = images.getJSONObject(i);

if (!image.isNull("url")) {
return image.getString("url");
}
}
}

return "";
}

Add getCategories

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// {"classifications" : [{"segment": {"name": "music"}}, ...]}
/**
* Get a set of categories from a JSONObject
* @param event
* @return A set of string
* @throws JSONException
*/
private Set<String> getCategories(JSONObject event) throws JSONException {
Set<String> categories = new HashSet<>();
if (!event.isNull("classifications")) {
JSONArray classifications = event.getJSONArray("classifications");
for (int i = 0; i < classifications.length(); i++) {
JSONObject classification = classifications.getJSONObject(i);
if (!classification.isNull("segment")) {
JSONObject segment = classification.getJSONObject("segment");
if (!segment.isNull("name")) {
String name = segment.getString("name");
categories.add(name);
}
}
}
}

return categories;
}

Add getItemList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Convert JSONArray to a list of item objects.
/**
* Convert JSONArray to a list of item objects
* @param events
* @return A list of Item objects
* @throws JSONException
*/
private List<Item> getItemList(JSONArray events) throws JSONException {
List<Item> itemList = new ArrayList<>();

for (int i = 0; i < events.length(); ++i) {
JSONObject event = events.getJSONObject(i);

ItemBuilder builder = new ItemBuilder();

if (!event.isNull("name")) {
builder.setName(event.getString("name"));
}

if (!event.isNull("id")) {
builder.setItemId(event.getString("id"));
}

if (!event.isNull("url")) {
builder.setUrl(event.getString("url"));
}

if (!event.isNull("rating")) {
builder.setRating(event.getDouble("rating"));
}

if (!event.isNull("distance")) {
builder.setDistance(event.getDouble("distance"));
}

builder.setCategories(getCategories(event));
builder.setAddress(getAddress(event));
builder.setImageUrl(getImageUrl(event));

itemList.add(builder.build());
}

return itemList;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Search the JSONArray results through TM API
* @param lat latitude
* @param lon longitude
* @param keyword keyword is optional
* @return JSONArray
*/
public List<Item> search(double lat, double lon, String keyword) {
List<Item> ret = new ArrayList<Item>();
if (keyword == null) keyword = DEFAULT_KEYWORD;
// translate keyword into URL-supported format
try {
keyword = java.net.URLEncoder.encode(keyword, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
// Get geoPoint
String geoHash = GeoHash.encodeGeohash(lat, lon, 8);
// Create query
// 50 is default search radius
String query = String.format("apikey=%s&geoPoint=%s&keyword=%s&radius=%s", API_KEY, geoHash, keyword, 50);
// Create URL
try {
// create a HTTP URL connection
HttpURLConnection connection = (HttpURLConnection) new URL(URL + "?" + query).openConnection();
// get the response code EG. 200/success, 404/fail
int responseCode = connection.getResponseCode();
// print res
System.out.println("\nSending \"GET\" request to URL : " + URL + "?" + query);
System.out.println("\nResponse Code: " + responseCode);
// check responseCode (Implement it later)
if (responseCode != 200) {

}
// read and write the response content
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
connection.disconnect();
// write the response to a JSON object
JSONObject obj = new JSONObject(response.toString());
// check the result
if (obj.isNull("_embedded")) {
return ret;
}
// get the events from the whole JSON and return the events field of it as a JSON Array.
JSONObject embedded = obj.getJSONObject("_embedded");
JSONArray events = embedded.getJSONArray("events");
ret = getItemList(events);
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}

Modify doGet() in searchItem Servlet


/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    double lat = Double.parseDouble(request.getParameter("lat"));
    double lon = Double.parseDouble(request.getParameter("lon"));

    String keyword = request.getParameter("term");
    TicketMasterAPI tmAPI = new TicketMasterAPI();
    List<Item> items = tmAPI.search(lat, lon, keyword);

    JSONArray array = new JSONArray();
    try {
        for (Item item : items) {
            JSONObject obj = item.toJSONObject();
            array.put(obj);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    RpcHelper.writeJSONArray(response, array);
}

Test result